from PyQt5.QtWidgets import QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QMessageBox
from database import Database
from main_view import MainWindow


class LoginWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.main_view = None
        self.register_btn = None
        self.login_btn = None
        self.password_input = None
        self.password_label = None
        self.username_input = None
        self.username_label = None
        self.db = Database()
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("登录/注册")
        self.setGeometry(300, 300, 300, 200)

        # 控件
        self.username_label = QLabel("用户名:")
        self.username_input = QLineEdit()
        self.password_label = QLabel("密码:")
        self.password_input = QLineEdit()
        self.password_input.setEchoMode(QLineEdit.Password)

        self.login_btn = QPushButton("登录")
        self.register_btn = QPushButton("注册")

        # 布局
        layout = QVBoxLayout()
        layout.addWidget(self.username_label)
        layout.addWidget(self.username_input)
        layout.addWidget(self.password_label)
        layout.addWidget(self.password_input)
        layout.addWidget(self.login_btn)
        layout.addWidget(self.register_btn)
        self.setLayout(layout)

        # 信号连接
        self.login_btn.clicked.connect(self.login)
        self.register_btn.clicked.connect(self.register)

    def login(self):
        username = self.username_input.text()
        password = self.password_input.text()
        if self.db.check_login(username, password):
            self.close()
            self.main_view = MainWindow()
            self.main_view.show()
        else:
            QMessageBox.warning(self, "错误", "用户名或密码错误")

    def register(self):
        username = self.username_input.text()
        password = self.password_input.text()
        if not username or not password:
            QMessageBox.warning(self, "错误", "用户名和密码不能为空")
            return
        if self.db.register_user(username, password):
            QMessageBox.information(self, "成功", "注册成功")
        else:
            QMessageBox.warning(self, "错误", "用户名已存在")

    def closeEvent(self, event):
        self.db.close()
        event.accept()